package com.example.myapplicationndk.indexlist;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.myapplicationndk.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * 自定义view 和  list 实现字母列表
 */
public class MainActivity2 extends AppCompatActivity {


    private String[] mLetters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R"
            , "S", "T", "U", "V", "W", "X", "Y", "Z", "#"};
    private TextView mTv;
    private APaintView.onTouch mOnTouch = new APaintView.onTouch() {
        @Override
        public void onTouch(String name) {
            Log.d("activityyyy", name);
            if (!TextUtils.isEmpty(name)) {
                mTv.setText(name);
                mTv.setVisibility(View.VISIBLE);
            }

        }

        @Override
        public void cancel() {
            mTv.setVisibility(View.GONE);
        }
    };
    private ListView mList;
    private RadioGroup rb_group;
    private Button clear;
    RadioButton rb_1;
    private String mCurrentTouchLetter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_index);


        rb_group = findViewById(R.id.rb_group);
        rb_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb = findViewById(checkedId);
                Log.d("checkid", rb.getText() + "");
            }
        });
        rb_1 = findViewById(R.id.rb_1);
        clear = findViewById(R.id.clear);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rb_1.setChecked(false);
            }
        });


        mTv = findViewById(R.id.tv_toast);

        APaintView ap = findViewById(R.id.ap);
        ap.setListener(mOnTouch);

        // list

        mList = findViewById(R.id.list);
        ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity2.this,
                R.layout.simple_expandable_list_item_1, mLetters) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                DisplayMetrics outMetrics = new DisplayMetrics();
                int heightPixels = mList.getMeasuredHeight();
                int perHeight = heightPixels / (mLetters.length);

                View v = LinearLayout.inflate(getApplicationContext(), R.layout.simple_expandable_list_item_1, null);

                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, perHeight);
                v.setLayoutParams(layoutParams);

                TextView t = v.findViewById(R.id.tv);
                t.setText(mLetters[position]);

                return super.getView(position, v, parent);
            }
        };

        mList.setAdapter(adapter);

        mList.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int position = ((ListView) v).pointToPosition((int) event.getX(), (int) event.getY());
                if (position < 0 || position >= 27) {
                    return false;
                }
                try {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                        case MotionEvent.ACTION_MOVE:
                            if (mOnTouch != null) {
                                mOnTouch.onTouch(mLetters[position]);
                            }
                            break;
                        case MotionEvent.ACTION_UP:
                            if (mOnTouch != null) {
                                mOnTouch.cancel();
                            }
                            break;
                    }
                } catch (Exception e) {

                } finally {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Looper.myLooper();
                            if (mTv.getVisibility() == View.VISIBLE) {
                                mTv.setVisibility(View.GONE);
                            }
                            Looper.loop();
                        }
                    }, 1000);
                }

                return false;
            }
        });

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        try {
            Rect rect = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            int statusBarHeight = rect.top;
            Log.d("psitionsss", getActionBarHeight(this) + " " + statusBarHeight);
            Rect mTouchFrame = null;
            int fingerY = (int) event.getY() - getActionBarHeight(this) - statusBarHeight;
            int singleHeight = mList.getMeasuredHeight() / mLetters.length;
            int position = (int) (fingerY / singleHeight);
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_MOVE:
                    Log.d("psitionsss", mLetters[position]);
                    if (mLetters[position].equals(mCurrentTouchLetter)) {
                        return true;
                    }
                    // 记录当前触摸的位置
                    mCurrentTouchLetter = mLetters[position];
                    Log.d("mCurrentTouchLetter", mCurrentTouchLetter);
                    if (mOnTouch != null) {
                        mOnTouch.onTouch(mCurrentTouchLetter);
                    } else {
                        Log.d("mCurrentTouchLetter", "null");
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    if (mOnTouch != null) {
                        mOnTouch.cancel();
                    } else {
                        Log.d("mCurrentTouchLetter", "null");
                    }
                    break;
            }

//            int po = getPositionfromXY(mList.getMeasuredHeight(), mLetters.length, event, true);
//            Log.d("possssss", po + " " + mLetters[po]);

        } catch (Exception e) {
            Log.d("positionsss", e.toString());
        }

        return super.onTouchEvent(event);
    }

    /**
     * 获取ActionBar 高度
     * 需要注意actionbar 是否存在
     *
     * @param context
     * @return
     */
    public static int getActionBarHeight(Activity context) {
        TypedValue tv = new TypedValue();
        if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            return TypedValue.complexToDimensionPixelSize(tv.data,
                    context.getResources().getDisplayMetrics());
        }
        return 0;
    }

    /**
     * 通过坐标获取index
     *
     * @param height
     * @param size
     * @param event
     * @return
     */
    public int getPositionfromXY(int height, int size, MotionEvent event, boolean isActionBar) {
        try {
            Rect rect = new Rect();
            int fingerY = -1;
            getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            int statusBarHeight = rect.top;
            Log.d("psitionsss", getActionBarHeight(this) + " " + statusBarHeight);
            Rect mTouchFrame = null;
            if (isActionBar) {
                fingerY = (int) event.getY() - getActionBarHeight(this) - statusBarHeight;
            } else {
                fingerY = (int) event.getY() - -statusBarHeight;
            }
            int singleHeight = height / size;
            return (int) (fingerY / singleHeight);
        } catch (Exception e) {
            Log.d("positionsss", e.toString());
        }
        return -1;
    }

}